#!/usr/bin/python
# -*- coding=utf8 -*-
from core.models.user import User
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from chtozadali.core.forms.login import AuthenticationForm
from chtozadali.core.forms.registration import RegistrationForm
from django.contrib.auth.decorators import login_required
from chtozadali.core.models.subject import Subject
from chtozadali.core.views.utilits import get_subjects

@login_required
def get_profile(request, id=False):
    if id:
        try:
            u = User.objects.get(id=id)
        except:
            u = request.user
    else:
        u = request.user
    return render(request, "profile.html", {"user_profile": u,
                                            "subjects": get_subjects(Subject.objects.all())})

def log_in(request):
    if request.method == "POST":
        form = AuthenticationForm(request.POST)
        print form.is_valid()
        if form.is_valid():
            u = authenticate(username=request.POST["username"], password=request.POST["password"])
            if u:
                return form.login(request)
            else:
                return render(request, "login.html", {"form_auth": form})
    else:
        form = AuthenticationForm()
    return render(request, "login.html", {"form_auth": form})

@login_required
def log_out(request):
    logout(request)
    return redirect("/")

def registration(request):
    if request.method == "POST":
        form_reg = RegistrationForm(request.POST)
        if form_reg.is_valid():
            form_reg.save()
            form_reg.login_user(request)
            return redirect("/")
    else:
        form_reg = RegistrationForm()
    return render(request, "registration.html", {"form_reg": form_reg})


